package com.hmdp.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.service.IShopTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@RestController
@RequestMapping("/shop-type")
public class ShopTypeController {
    @Resource
    private IShopTypeService typeService;
    @Resource
    StringRedisTemplate stringRedisTemplate;

    @GetMapping("list")
    public Result queryTypeList() {
        List<ShopType> list;
        String key = CACHE_SHOPTYPE_KEY + "list";
        String keyJson = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(keyJson)) {
            list = JSONUtil.toList(keyJson, ShopType.class);
            return Result.ok(list);
        } else if (keyJson != null) {
            return Result.fail("不存在店铺类型！");
        }
        list = typeService
                .query().orderByAsc("sort").list();
        if (list == null) {
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            return Result.fail("不存在店铺类型！");
        }
        String jsonStr = JSONUtil.toJsonStr(list);
        stringRedisTemplate.opsForValue().set(key, jsonStr, CACHE_SHOPTYPE_TTL, TimeUnit.MINUTES);
        return Result.ok(list);
    }
}
